﻿using System;
using DBProvider.Providers;
using System.Web;

namespace HealthCommunity
{
	public partial class Login : System.Web.UI.Page
	{
		private const string CONST_LOGINUSERNAME = "loginusername";

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				if (HttpContext.Current.Request.Cookies[CONST_LOGINUSERNAME] != null && !(string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[CONST_LOGINUSERNAME].Value)))
				{
					txtUserName.Text = HttpContext.Current.Request.Cookies[CONST_LOGINUSERNAME].Value;
				}

				txtUserName.Focus();
			}
		}

		protected void btnLogin_Click(object sender, EventArgs e)
		{
			var userName = txtUserName.Text.Trim();
			var pwd = txtPwd.Text.Trim();

			if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd))
			{
				try
				{
					var userProvider = new UserProvider();
					var msg = string.Empty;
					if (userProvider.ValidUser(userName, pwd, out msg))
					{
						var u = userProvider.GetUser(userName);
						SiteContext.SetCookie(HttpContext.Current.ApplicationInstance, SiteContext.CONST_USERSESSIONCOOKIE, u.UserID.ToString());
						if (chkRememberme.Checked)
						{
							SiteContext.SetCookie(HttpContext.Current.ApplicationInstance, CONST_LOGINUSERNAME, u.UserName);
						}
						Response.Redirect("Home.aspx");
					}
					else
					{
						ltrMsg.Text = "登入失败: " + msg;
					}
				}
				catch (Exception exc)
				{
					ltrMsg.Text = exc.Message;
				}
			}
		}
	}
}